<?php

namespace app\console\command;

use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\Db;
use think\Log;

class CollectionSnackShort extends Command
{
    private $appToken = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJ3ZWJtYW4udGlueXdhbi5jbiIsImF1ZCI6IndlYm1hbi50aW55d2FuLmNuIiwiaWF0IjoxNzI1ODk0NzAyLCJuYmYiOjE3MjU4OTQ3MDIsImV4cCI6MTcyNjQ5OTUwMiwiZXh0ZW5kIjp7ImlkIjoxNDQyMDMzLCJwYWNrYWdlX2lkIjoiMSIsInVzZXJUeXBlIjoiV2ViVXNlciJ9fQ.Q80g55X_e-avPi2G3cSLxQrxgGvoMjJLCwX1kiXxvos';

    protected function configure()
    {
        $this->setName('collection_snack_short')
            ->setDescription('collection_snack_short video files');
    }

    protected function execute(Input $input, Output $output)
    {
        $output->info("execute collection_snack_short");

        $ipInfo = geoip('61.128.128.68')->toArray();
        exit();

//        $bookNo = 'AUHGAIIuqqWOmb30hNPSYA==';
//        $bookInfo = Db::name('snackshow_book')->where('book_no', $bookNo)->find();
//        if (empty($bookInfo)) {
//            exit();
//        }

//        $bookList = Db::name('snackshow_book')->whereRaw('id < 10')->select();
//        $bookList = Db::name('snackshow_book')->whereRaw('id = 36')->select();
        $bookList = Db::name('snackshow_book')->select();
        foreach ($bookList as $bookInfo) {
            $bookNo = $bookInfo['book_no'];
            $dirPath = 'snackshow/' . strtoupper(md5($bookNo));
            if (!file_exists($dirPath)) {
                mkdir($dirPath);
            }

            $cover_image = $bookInfo['cover_image'];
//            $coverFile = strtoupper(md5($bookNo)) . '/' . substr(strrchr($cover_image, '/'), 1);
            $coverFile = $dirPath . '/' . $bookInfo['book_name'] . '.' . substr(strrchr($cover_image, '.'), 1);
            if (!file_exists($coverFile)) {
                file_put_contents($coverFile, file_get_contents($cover_image));
            }

            // 循环更新免费剧集URL
//            $chapterList = Db::name('snackshow_chapter')->where('book_no', $bookInfo['book_no'])->where('chapter_price', 80)->select();
            $chapterList = Db::name('snackshow_chapter')->where('book_no', $bookInfo['book_no'])->whereRaw('play_url is null')->select();
            foreach ($chapterList as $chapterItem) {
                $filepath = 'snackshow/log/' . md5($bookNo) . '-' . $chapterItem['chapter_order'] . '.txt';
//            if (!file_exists($filepath)) {
                $url = '/web/book/detail';
                $params = null;
                $params['bookNo'] = $chapterItem['book_no'];
                $params['chapterNo'] = $chapterItem['chapter_no'];
                $html = $this->get($url, $params);
                $json = json_decode($html, true);
                file_put_contents($filepath, $html);
//            } else {
//                $html = file_get_contents($filepath);
//                $json = json_decode($html, true);
//            }
//                var_dump($json['data']['currentChapter']);
//                exit();

                if (!empty($json['data']['currentChapter'])) {
                    $currentChapter = $json['data']['currentChapter'];
//                                    var_dump($currentChapter);

                    if ($currentChapter['chapter_no'] != $chapterItem['chapter_no']) {
                        echo $bookInfo['book_name'] . ' ' . $chapterItem['chapter_order'] . ' <> ' . $currentChapter['chapter_no'] . PHP_EOL;
                        continue;
                    }

                    $chapterInfo = Db::name('snackshow_chapter')->where('chapter_no', $currentChapter['chapter_no'])->find();
                    if (!empty($chapterInfo)) {
//                                    var_dump($chapterInfo);
                        if (empty($currentChapter['play_url'])) {
                            echo $bookInfo['book_name'] . ' ' . $chapterItem['chapter_order'] . ' null' . PHP_EOL;
                            continue;
                        }
                        $up = null;
                        $up['play_url'] = $currentChapter['play_url'];
                        $up['like_count'] = $currentChapter['statistics']['like_count'];
                        $up['share_count'] = $currentChapter['statistics']['share_count'];
                        Db::name('snackshow_chapter')->where('chapter_no', $currentChapter['chapter_no'])->update($up);

//                    $command = 'D:\ffmpeg-master-latest-win64-gpl\bin\ffmpeg -i "' . $currentChapter['play_url'] . '" -c copy -bsf:a aac_adtstoasc ' . $dirPath . '/' . str_pad($chapterInfo['chapter_order'], 2, 0, STR_PAD_LEFT) . '.mp4';
                        $outputFile = $dirPath . '/' . str_pad($chapterInfo['chapter_order'], 2, 0, STR_PAD_LEFT) . '.mp4';
                        $command = 'D:\project\duanju\duanju\ffmpeg -i "' . $currentChapter['play_url'] . '" -c copy -bsf:a aac_adtstoasc ' . $outputFile;
                        echo $command . PHP_EOL;
                        if (!file_exists($outputFile)) {
                            $output = shell_exec($command);
                            echo $output . PHP_EOL;
                        }
//                    exit();
                    }
                }
            }
        }

        exit();

//        $url = 'https://api.snackshow.tv/web/book/detail?bookNo=No0Mq/ekdpCjQbpocM3Q/Q==';
//
//        $html = file_get_contents($url);
//
//        echo $html;
//
//        var_dump(json_decode($html));
//
//        exit();


//        $url = 'https://snackshort.tv/wallet';

        $content = file_get_contents('t.txt');

//        $html = strstr($html, '<script type="application/json" id="__NUXT_DATA__" data-ssr="true">');
//        $html = strstr($html, '</script>', true);

//        echo $content;

        $json = json_decode($content);

        foreach ($json as $key => $item) {

            if (is_string($item)) {
                if (preg_match('/.*==/is', $item, $result)) {

                    if ($result) {
                        $bookNo = $result[0];
                        $filepath = 'snackshow/' . md5($bookNo) . '.txt';
                        if (!file_exists($filepath)) {
                            $url = '/web/book/detail';
                            $params = null;
                            $params['bookNo'] = $bookNo;
                            $html = $this->get($url, $params);
                            $json = json_decode($html, true);
//                        file_put_contents('snackshow/' . md5($bookNo) . '-' . $json['data']['book']['book_name'] . '.txt', $html);
                            file_put_contents($filepath, $html);
                        } else {
                            $html = file_get_contents($filepath);
                            $json = json_decode($html, true);
                        }

//                        var_dump($json);
                        if (!empty($json['data']['book'])) {
                            $book = $json['data']['book'];
//                            var_dump($book);
                            $bookInfo = Db::name('snackshow_book')->where('book_no', $book['book_no'])->find();
//                            var_dump($bookInfo);
                            if (empty($bookInfo)) {
                                Db::name('snackshow_book')->insert($book);
                            }

                            if (!empty($json['data']['chapters'])) {
                                $chapters = $json['data']['chapters'];
                                foreach ($chapters as $chapter) {
                                    $chapterInfo = Db::name('snackshow_chapter')->where('chapter_no', $chapter['chapter_no'])->find();
                                    if (empty($chapterInfo)) {
                                        $chapterRow = $chapter;
                                        unset($chapterRow['is_lock'], $chapterRow['is_free']);
                                        $chapterRow['book_no'] = $book['book_no'];
//                                        var_dump($chapterRow);
                                        Db::name('snackshow_chapter')->insert($chapterRow);
                                    }
                                }
                            }

                            if (!empty($json['data']['currentChapter'])) {
                                $currentChapter = $json['data']['currentChapter'];
//                                var_dump($currentChapter);
                                $chapterInfo = Db::name('snackshow_chapter')->where('chapter_no', $currentChapter['chapter_no'])->find();
                                if (!empty($chapterInfo)) {
//                                    var_dump($chapterInfo);
                                    $up = null;
                                    $up['play_url'] = $currentChapter['play_url'];
                                    $up['like_count'] = $currentChapter['statistics']['like_count'];
                                    $up['share_count'] = $currentChapter['statistics']['share_count'];
                                    Db::name('snackshow_chapter')->where('chapter_no', $currentChapter['chapter_no'])->update($up);
                                }
                            }

                            // 循环更新免费剧集URL

                            $chapterList = Db::name('snackshow_chapter')->where('book_no', $book['book_no'])->where('chapter_price', 0)->select();
                            foreach ($chapterList as $chapterItem) {
                                $filepath = 'snackshow/' . md5($bookNo) . '-' . $chapterItem['chapter_order'] . '.txt';
                                if (!file_exists($filepath)) {
                                    $url = '/web/book/detail';
                                    $params = null;
                                    $params['bookNo'] = $chapterItem['book_no'];
                                    $params['chapterNo'] = $chapterItem['chapter_no'];
                                    $html = $this->get($url, $params);
                                    $json = json_decode($html, true);
                                    file_put_contents($filepath, $html);
                                } else {
                                    $html = file_get_contents($filepath);
                                    $json = json_decode($html, true);
                                }

                                if (!empty($json['data']['currentChapter'])) {
                                    $currentChapter = $json['data']['currentChapter'];
//                                    var_dump($currentChapter);
                                    $chapterInfo = Db::name('snackshow_chapter')->where('chapter_no', $currentChapter['chapter_no'])->find();
                                    if (!empty($chapterInfo)) {
//                                    var_dump($chapterInfo);
                                        $up = null;
                                        $up['play_url'] = $currentChapter['play_url'];
                                        $up['like_count'] = $currentChapter['statistics']['like_count'];
                                        $up['share_count'] = $currentChapter['statistics']['share_count'];
                                        Db::name('snackshow_chapter')->where('chapter_no', $currentChapter['chapter_no'])->update($up);

//                                        echo 'D:\ffmpeg-master-latest-win64-gpl\bin\ffmpeg -i "' . $currentChapter['play_url'] . '" -c copy -bsf:a aac_adtstoasc ' . md5($bookNo) . '/' . $chapterInfo['chapter_order'] . '.mp4' . PHP_EOL;
                                    }
                                }
                            }

                        }

//                        exit();
                    }

                }
            }

        }

        exit();

//        var_dump($json);

        $result = null;

        foreach ($json as $key => &$item) {
            echo "------------------------";
            echo '$key = ' . $key . PHP_EOL;
            echo PHP_EOL;
//            var_dump($item);
            echo PHP_EOL;

            if (is_array($item)) {

                foreach ($item as $subKey => $subItem) {
                    echo "------------------------------------------------";
                    echo '$subKey = ' . $subKey . PHP_EOL;
                    echo PHP_EOL;
                    var_dump($subItem);
                    echo PHP_EOL;
                    if (is_int($subItem)) {
                        echo '$item[' . $subItem . '] ' . PHP_EOL;
                        echo PHP_EOL;
                        var_dump($json[$subItem]);
                        echo PHP_EOL;
                        $item[$subKey] = $json[$subItem];
                        echo PHP_EOL;
                    }
                }

            }

            if (is_object($item)) {
                var_dump($item);
                foreach ($item as $subKey => $subItem) {
                    var_dump($subKey);
                    var_dump($subItem);
                    if (is_int($subItem)) {
                        $item->$subKey = $json[$subItem];
                    }
                }
                var_dump($item);
            }

        }

        var_dump($json[0]);

    }

    /**
     * 获取API接口URL根地址
     *
     * @return string
     */
    public function getApiUrl($path)
    {
        return "https://api.snackshow.tv" . $path;
    }

    /**
     * 发送请求
     * @param $apiPath
     * @param array $params
     * @param string $requestType
     * @param string $headers
     * @return mixed
     */
    public function request($apiPath, $params = [], $requestType = 'POST', $headers = '')
    {
        $url = $this->getApiUrl($apiPath);

        Log::info('SnackShort request,url:' . $url . ',params:' . json_encode($params));

        $timeout = 30;
        $params_encode = json_encode($params);

        //根据请求类型设置特定参数
        $opts = array(
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_TIMEOUT => $timeout,
            CURLOPT_RETURNTRANSFER => 1,
            CURLOPT_URL => $url,
            CURLOPT_SSL_VERIFYHOST => 0,
            CURLOPT_SSL_VERIFYPEER => 0,
        );
        if ($headers != "") {
            $opts[CURLOPT_HTTPHEADER] = $headers;
        } else {
            $opts[CURLOPT_HTTPHEADER] = [
                'Content-type: application/json',
                'Authorization: Bearer ' . $this->appToken,
            ];
        }
        switch (strtoupper($requestType)) {
            case "GET" :
                $opts[CURLOPT_HTTPGET] = true;
                $opts[CURLOPT_URL] = $url . '?' . http_build_query($params);
                $opts[CURLOPT_ENCODING] = '';
                $opts[CURLOPT_CUSTOMREQUEST] = 'GET';
                break;
            case "POST":
                $opts[CURLOPT_POST] = true;
                $opts[CURLOPT_CUSTOMREQUEST] = "POST";
                $opts[CURLOPT_POSTFIELDS] = $params_encode;
                break;
            case "PUT" :
                $opts[CURLOPT_CUSTOMREQUEST] = "PUT";
                $opts[CURLOPT_POSTFIELDS] = $params_encode;
                break;
            case "DELETE":
                $opts[CURLOPT_CUSTOMREQUEST] = "DELETE";
                $opts[CURLOPT_POSTFIELDS] = $params_encode;
                break;
            default:
                throw new Exception('不支持的请求方式！');
        }
        /* 初始化并执行curl请求 */
        $ch = curl_init();
        curl_setopt_array($ch, $opts);

        $result = curl_exec($ch);
        $err = curl_error($ch);
        curl_close($ch);
        if (!empty($err)) {
            Log::error('cloudflare api request:' . json_encode($result) . ',error:' . json_encode($err));
        }
        return $result;
        return json_decode($result, true);
    }

    /**
     * post请求
     * @param $apiPath
     * @param array $params
     * @param string $headers
     * @return mixed
     */
    public function post($apiPath, $params = [], $headers = '')
    {
        return $this->request($apiPath, $params, 'POST', $headers);
    }


    /**
     * get请求
     * @param $apiPath
     * @param array $params
     * @param string $headers
     * @return mixed
     */
    public function get($apiPath, $params = [], $headers = '')
    {
        return $this->request($apiPath, $params, 'GET', $headers);
    }

    /**
     * put请求
     * @param $apiPath
     * @param array $params
     * @param string $headers
     * @return mixed
     */
    public function put($apiPath, $params = [], $headers = '')
    {
        return $this->request($apiPath, $params, 'PUT', $headers);
    }

    /**
     * delete请求
     * @param $apiPath
     * @param array $params
     * @param string $headers
     * @return mixed
     */
    public function delete($apiPath, $params = [], $headers = '')
    {
        return $this->request($apiPath, $params, 'DELETE', $headers);
    }
}
